<template>
   <view class="common-wrapper">
       <view class="shopping-wrapper" v-if="bookList.length">
           <view class="shop-tips">{{tips}}</view>
           <mescroll-uni :fixed="false" @down="downCallback" @up="upCallback" :down="downOption" :up="upOption"  class="message" @init="mescrollInit">
               <view
                       class="common-interval book-list"
                       v-for="(item, index) in bookList"
                       :key="item.booksId"
                       :data-index="index"
               >
                   <shop-item
                           :item="item"
                           :ref="`ref${index}`"
                           :checked="checkedIds.includes(item.booksId)"
                           :index="index"
                           :delIndex="del === index"
                           @selectBook="selectBook"
                           @delIndex="delIndex"
                           @delItem="delItem"
                   />
               </view>
           </mescroll-uni>
           <view class="shoping-bottom fix" v-if="!hidePart">
               <image @tap.stop="checkAll" class="common-choose check-btn" :src="http+(isCheckAll?'choose-active':'choose')+'.png'"/>
               <view class="check-num">
                   <view>全选 （共{{shoppingNum}}）本</view>
                   <view style="font-size: 24rpx; color: #999999; margin-top: 6rpx;">已选{{bookNum}}书位</view>
               </view>
               <text class="del-btn" @click="delBooks">删除</text>
               <text class="borrow-btn"  @click="goBorrow">去借阅</text>
               <!--<text v-if="checkedIds.length" style="margin-left: 4rpx; font-size: 18rpx;">{{bookNum}}书位</text>-->
           </view>
           <gw-show-modal
                   v-model="showModal"
                   :type="modalObj[showModalType].type"
                   :width="modalObj[showModalType].width"
                   :height="modalObj[showModalType].height"
                   :tipsContent="modalObj[showModalType].content"
                   @cancel="cancelHandle"
                   @confirm="confirmHandle">
              <view style="position: relative;">
                  <image src="https://img.thumbrary.com/vipTips.png" style="width: 690rpx; height: 750rpx;"/>
                  <view class="open-membership" @tap.stop="openMemberShip"/>
                  <view class="close-wrapper">
                      <text class="one one-close close-btn" @tap="showModal=false"/>
                  </view>
              </view>
           </gw-show-modal>
       </view>
       <view v-else class="none-data">
           <image src="../../static/imgs/none-data.png"/>
           <view class="none-data-txt">{{login ? '您的书筐空空如也~' : '您还没登录，请先登录'}}</view>
           <view class="none-data-btn" @tap="goHome">{{login ? '去首页看看' : '登录'}}</view>
       </view>
       <gw-user-login ref="userLogin" modalType="login" @loginSuccess="getBooks"/>
   </view>
</template>

<script>
    import shopItem from './shopItem'
    import service from "@/service";
    import gwShowModal from '../components/gw-show-modal'
    import MescrollUni from "@/components/mescroll-uni/mescroll-uni.vue";
    import gwUserLogin from '@/pages/components/gw-user-login'
    import { mapGetters } from 'vuex';
    import { getBooks, getConfInfo, getShoppingNum } from '@/util/commonFn'
    export default {
        name: "index",
        components: {
            shopItem, gwShowModal, MescrollUni, gwUserLogin
        },
        computed: {
            ...mapGetters(['login', 'vipCardNum', 'shoppingNum', 'hidePart'])
        },
        data(){
            return{
                isCheckAll: false,
                showtips: false,
                http: this.$https,
                page: 1,
                limit: 10,
                del: -1,
                itemId: '',
                showModal: false,
                showModalType: 'custom', // thumVip2 会员卡达到上限
                showModalWidth: '690rpx', // thumVip2 560
                showModalHeight: '900rpx', // thumVip2 486
                modalObj: {
                    del: {
                        content: '确认删除所选书籍？',
                        type: 'tips',
                        width: '550rpx',
                        height: '260rpx'
                    },
                    borrow: {
                        content: ``,
                        type: 'tips',
                        width: '550rpx',
                        height: '260rpx'
                    },
                    custom: {
                        content: '',
                        type: 'custom',
                        width: '690rpx',
                        height: '900rpx'
                    },
                },
                checked: false,
                tips: '',
                maxBookNum: '',
                bookNum: 0,
                checkedIds: [],
                bookList: [],
                tipsContent: '确认删除所选书籍？',
                downOption: {
                    auto: false,
                },
                upOption:{
                    use: true, // 是否启用上拉加载; 默认true
                    auto: true, // 是否在初始化完毕之后自动执行上拉加载的回调; 默认true
                    page: {
                        num: 0, // 当前页码,默认0,回调之前会加1,即callback(page)会从1开始
                        size: 10 // 每页数据的数量,默认10
                    },
                    noMoreSize: 5, // 配置列表的总数量要大于等于5条才显示'-- END --'的提示
                    empty: {
                        icon: 'https://img.thumbrary.com/empty.png',
                        tip: '暂无数据'
                    },
                    offset: 130,
                    textNoMore:'我是有底线的 >_<'
                },
                mescroll: null
            }
        },
        methods: {
            mescrollInit(mescroll) {
                this.mescroll = mescroll;
            },
            downCallback(mescroll){
                this.bookList = [];
                this.page = 1;
                mescroll.resetUpScroll();
            },
            upCallback(mescroll){
                this.page = mescroll.num;
                this.getBooks();
            },
            test(){},
            getBooks () {
                let params = {
                    type: 2,
                    page: this.page,
                    limit: this.limit
                }
                getBooks(params).then(result=>{
                    let data = result.data || [];
                    this.page > 1 ? this.bookList.push(...data) : this.bookList = data;
                    this.mescroll && this.mescroll.endBySize(data.length, result.num);
                });
            },
            delIndex(index){
                this.del = index
            },
            selectBook(item){
                if(!this.checkedIds.includes(item.booksId)){
                    this.checkedIds.push(item.booksId);
                    this.bookNum = Number(this.bookNum) + item.booksNum
                } else{
                    this.checkedIds = this.checkedIds.filter(val => val !== item.booksId)
                    this.bookNum = Number(this.bookNum) - item.booksNum
                }
                this.isCheckAll = (this.checkedIds.length === this.shoppingNum);
            },
            checkAll(){
                if(!this.isCheckAll){
                    this.checkAllNum();
                } else {
                    this.checkedIds = [];
                    this.bookNum = 0;
                }
                this.isCheckAll = !this.isCheckAll;
                this.checked = this.isCheckAll;
            },
            checkAllNum(){
                uni.showLoading({
                    title: '',
                });
                service.homeService.shoppingAll({
                    data: {},
                    success: res => {
                        uni.hideLoading();
                        if (res.code === 200) {
                            this.bookNum = res.result.booksNum || 0;
                            this.checkedIds = res.result.booksIdArray || [];
                        } else {
                            uni.showToast({
                                title: `${res.resultMsg}`,
                                duration: 2500,
                                icon: 'none'
                            });
                        }
                    },
                    fail: ()=>{
                        uni.hideLoading();
                    },
                    complete: () => {
                    }
                });
            },
            delItem(item, index){
                this.showModal = true;
                this.showModalType = 'del';
                this.itemId = item.booksId
            },
            delBooks(){
                if(!this.checkedIds.length){
                    uni.showToast({
                        title: `请先选择要删除的书籍哦！`,
                        duration: 2500,
                        icon: 'none'
                    });
                    return;
                }
                this.showModal = true;
                this.showModalType = 'del';
            },
            confirmHandle(){
                this.showModal = false;
                if(this.showModalType === 'borrow') return;
                !this.itemId ? this.delHandle(this.checkedIds, 'isAll') : this.delHandle([this.itemId])
            },
            cancelHandle(){
                this.del = -1
            },
            delHandle(ids, isAll){
                uni.showLoading({
                    title: '',
                });
                service.homeService.delShopping({
                    data: {
                        booksId: ids
                    },
                    success: res => {
                        uni.hideLoading();
                        if (res.code === 200) {
                            uni.showToast({
                                title: `删除成功`,
                                duration: 2500,
                                icon: 'none'
                            });
                            if(isAll){
                                this.isCheckAll = false;
                                this.checkedIds = [];
                            }else{
                                this.del = -1
                                if(this.checkedIds.includes(this.itemId)) {
                                    let idx = this.checkedIds.indexOf(this.itemId)
                                    this.checkedIds.splice(idx, 1)
                                }
                            }
                            this.page = 1;
                            this.getBooks();
                            getShoppingNum();
                            this.itemId = ''
                        } else {
                            uni.showToast({
                                title: `${res.resultMsg}`,
                                duration: 2500,
                                icon: 'none'
                            });
                        }
                    },
                    fail: ()=>{
                        uni.hideLoading();
                    },
                    complete: () => {
                    },
                });
            },
            // 开通会员
            openMemberShip(){
                uni.navigateTo({
                    url: '/pagesMine/vip/index'
                });
            },
            // 借阅
            goBorrow(){
                // 没有选择的情况
                if(!this.checkedIds.length){
                    uni.showToast({
                        title: `请先选择借阅的书籍哦！`,
                        duration: 2500,
                        icon: 'none'
                    });
                    return;
                }

                // 没有会员的情况
                if(!this.vipCardNum){
                    this.showModalType = 'custom';
                    this.showModal = true;
                    return;
                }

                // 借阅数量大于最大数量时
                if(this.bookNum > this.maxBookNum){
                    this.showModalType = 'borrow';
                    this.showModal = true;
                    return;
                }

                uni.showLoading({
                    title: '加载中',
                });
                service.mineService.booksOrder({
                    data: {
                        booksIdArr: this.isCheckAll ? '' : this.checkedIds
                    },
                    success: res => {
                        uni.hideLoading();
                        if (res.code === 200) {
                            uni.navigateTo({
                                url: `../../pagesShopping/order/order-detail?orderId=${res.result.orderId}`
                            })
                        } else {
                            uni.showToast({
                                title: `${res.resultMsg}`,
                                duration: 2500,
                                icon: 'none'
                            });
                        }
                    },
                    fail: ()=>{
                        uni.hideLoading();
                    },
                    complete: () => {
                    },
                    method: 'POST'
                });
            },
            clickCancel(){},
            clickConfirm(){},
            goHome(){
                if(!this.login){
                    this.$refs.userLogin.showModal = true;
                    return;
                }
                uni.switchTab({
                    url: '/pages/index/index'
                });
            },
        },
        onShow(){
            if(!this.login){
                this.bookList = [];
                this.$refs.userLogin.showModal = true;
                this.bookList = [];
                return;
            }else{
                this.$refs.userLogin.showModal = false;
            }
            if(this.shoppingNum){
                uni.setTabBarBadge({
                    index: 2,
                    text: `${this.shoppingNum}`
                });
            } else {
                uni.removeTabBarBadge({
                    index: 2
                })
            }
            this.page = 1;
            this.checkedIds = [];
            this.bookNum = 0;
            this.del = -1
            this.isCheckAll = false;
            this.mescroll && this.mescroll.resetUpScroll();
            this.getBooks();
        },
        onHide(){
            // this.isCheckAll = false
        },
        mounted() {
            let that = this;
            getConfInfo().then(res => {
                that.tips = res.schoppingTips
                that.maxBookNum = res.maxBookNum
                that.modalObj.borrow.content = `最多只能借阅${that.maxBookNum}书位哦！`
            })
        }
    }
</script>

<style scoped lang="scss">
    .shopping-wrapper{
        height: 100%;
        background:#F2F5F7;
        box-sizing: border-box;
        .open-membership{
            width: 380rpx;
            height: 88rpx;
            position: absolute;
            bottom: 280rpx;
            left: 200rpx;
        }
        .close-wrapper{
            font-size: 60rpx;
            color: #ffffff;
            text-align: center;
            height: 150rpx;
            line-height: 150rpx;
            /*margin-left: 80rpx;*/
        }
        .shop-tips{
            width:750rpx;
            top: 0;
            height:48rpx;
            line-height: 48rpx;
            text-align: center;
            background:rgba(252,87,98,0.2);
            font-size:28rpx;
            color:rgba(252,87,98,1);
            font-weight: 400;
        }
        .book-list{
            background: #F2F5F7;
        }
        .shoping-bottom{
            width:750rpx;
            height:110rpx;
            background:rgba(255,255,255,1);
            bottom: 0rpx;
            display: flex;
            align-items: center;
            .check-btn{
                font-size: 42rpx;
                margin-left: 60rpx;
            }
            .check-num{
                font-size:28rpx;
                font-weight: 500;
                color:rgba(51,51,51,1);
                margin-left: 20rpx;
            }
            .del-btn{
                margin-left: 66rpx;
                font-size:28rpx;
                font-weight:500;
                color:rgba(153,153,153,1);
            }
            .borrow-btn{
                font-size:28rpx;
                font-weight:500;
                color:rgba(255,255,255,1);
                width: 240rpx;
                height: 88rpx;
                display: flex;
                align-items: center;
                justify-content: center;
                background:rgba(43,168,252,1);
                border-radius:44rpx;
                margin-left: 30rpx;
            }
        }
    }
    .none-data{
        padding: 200rpx 173rpx;
        font-size: 30rpx;
        text-align:center;
        background: #fff;
        image{
            width: 404rpx;
            height: 400rpx;
        }
        &-txt{
            margin-top: 58rpx;
            color:#999999;
        }
        &-btn{
            margin-top: 30rpx;
            color: #2BA8FC;
        }
    }
</style>
